package com.hfzy.ihk.common.core.elasticsearch;

import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

/**
 * Created by Administrator on 2018/3/19.
 *
 * @author wws
 */
public class ElasticsearchScripts {

    public static final String paramValueField = "p_Val";
    public static final String paramVersionValueField = "p_version_Val";

    public static final String versionUp = "ctx._source.version+=params.p_Val";

    public static String addToListTemplate_old =
            "if(ctx._source.{}==null) { " +
                "if(params.p_Val instanceof List){" +
                    "ctx._source.{}=params.p_Val;" +
                    "ctx._source.{}=params.p_version_Val;" +
                "}else{" +
                    "ctx._source.{}=[params.p_Val];" +
                    "ctx._source.{}=params.p_version_Val;" +
                    "}" +
            "}else{" +
                "if(params.p_Val instanceof List){" +
                    "ctx._source.{}.addAll(params.p_Val);" +
                    "ctx._source.{}=params.p_version_Val;" +
                "}else{" +
                    "ctx._source.{}.add(params.p_Val);" +
                    "ctx._source.{}=params.p_version_Val;" +
                 "}" +
            "}";

    public static String createAddToListTemplateOld(String updateFieldName,String versionFieldName) {
        return formatStr(addToListTemplate_old,
                updateFieldName,updateFieldName,versionFieldName,
                updateFieldName,versionFieldName,
                updateFieldName,versionFieldName,
                updateFieldName,versionFieldName);
    }

    public static String addToListTemplate =
            "if(ctx._source.{}==null) { " +
                "if(params.p_Val instanceof List){" +
                    "ctx._source.{}=params.p_Val;" +
                "}else{" +
                    "ctx._source.{}=[params.p_Val];" +
                    "}" +
            "}else{" +
                "if(params.p_Val instanceof List){" +
                    "ctx._source.{}.addAll(params.p_Val);" +
                "}else{" +
                    "ctx._source.{}.add(params.p_Val);" +
                 "}" +
            "}";
    public static String createAddToListTemplate(String updateFieldName) {
        return formatStr(addToListTemplate,updateFieldName,updateFieldName,updateFieldName,updateFieldName,updateFieldName);
    }


    private static String formatStr(String format, Object... argArray) {
        FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
        return ft.getMessage();
    }

}
